package com.atguigu.lease.common.utils;

import ch.qos.logback.core.net.server.Client;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import org.apache.ibatis.ognl.Token;

import javax.crypto.SecretKey;
import java.util.Date;

public class JwtUtil {
    //必须要32位才行,要不然太短,报错,提到外面,解析jwt也要用.
    private static SecretKey key = Keys.hmacShaKeyFor("vZ5oD9hP8kS0yU8pE4mC8cP1uG5kH4pU".getBytes());
    public static String createToken(long userId){

        //指定时间过期(payload自带属性),可根据加一个时间来达到有效时间期限.
        String token = Jwts.builder().setExpiration(new Date(System.currentTimeMillis() + 360000000))
                .signWith(key, SignatureAlgorithm.HS256).claim("userId", userId).compact();
        return token;
    }

    public static Claims parseToken(String token){
        if (token==null){
            throw new LeaseException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
        }
        try {
            //key要和createToken是同一个key
            JwtParser jwtParser = Jwts.parserBuilder().setSigningKey(key).build();
            Jws<Claims> claimsJws = jwtParser.parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            return claims;
        }catch (ExpiredJwtException e){
            throw new LeaseException(ResultCodeEnum.TOKEN_EXPIRED);
        }catch (JwtException e){
            throw new LeaseException(ResultCodeEnum.TOKEN_INVALID);
        }

    }
//    public static void main(String[] args) {
//        String jwt = createJwt(2L, "user");
//        System.out.println(jwt);
//    }
}
